using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using Rotempco.Core.Web.CRUD.Objects;
using Rotempco.Core.Web.Logic;

namespace Rotempco.Core.Web.CRUD.Logic
{
    public class PageListContainerHelper
    {
        public static PageListContainer GenerateContainer<TDomainObject>(List<TDomainObject> domainObjectList, List<string> headerList, List<string> parameterList, string identifierPropertyName, string editUrl = null, string deleteUrl = null, bool hideAddNewButton = false)
        {
            PageListContainer pageListContainer = new PageListContainer();
            pageListContainer.Headers = headerList;
            pageListContainer.DetailRows = new List<PageListContainerRow>();
            pageListContainer.EditUrl = editUrl;
            pageListContainer.DeleteUrl = deleteUrl;
            pageListContainer.HideAddNewButton = hideAddNewButton;

            Type domainObjectType = typeof(TDomainObject);

            foreach (TDomainObject domainObject in domainObjectList)
            {
                PageListContainerRow detailRow = new PageListContainerRow();
                detailRow.Id = long.Parse(domainObjectType.GetProperty(identifierPropertyName).GetValue(domainObject, null).ToString());
                detailRow.PropertyValueList = new List<string>();

                foreach (string parameter in parameterList)
                {
                    PropertyInfo propertyInfo = domainObjectType.GetProperty(parameter);

                    string propertyValue;
                    if (propertyInfo.PropertyType == typeof(DateTime))
                        propertyValue = WebConvertHelper.ToDate(propertyInfo.GetValue(domainObject, null));
                    if (propertyInfo.PropertyType == typeof(bool))
                        propertyValue = WebConvertHelper.ToCheckbox(propertyInfo.GetValue(domainObject, null));
                    else
                        propertyValue = propertyInfo.GetValue(domainObject, null).ToString();

                    detailRow.PropertyValueList.Add(propertyValue);
                }

                pageListContainer.DetailRows.Add(detailRow);
            }

            return pageListContainer;
        }
    }
}